﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.UI.Models;
using ARR.Entities;
using System.Collections.ObjectModel;
using System.Windows.Input;
using ARR.UI.Commands;
using ARR.UI.Helpers;
using ARR.UI.Views;
using ARR.Shared;

namespace ARR.UI.ViewModels
{
    public class ArticleMasterSplitPopupViewModel : ViewModelBase
    {
        private IArticleMasterModel model;

        private ICommand cancelCommand;
        private ICommand splitCommand;
        private ICommand selectCommand;
        private ICommand removeArticleCommand;
        private ICommand searchCommand;
        private List<Article> leftArticles;
        private List<Article> rightArticles;

        public ArticleMasterSplitPopupViewModel(IArticleMasterModel model, Article selectedArticle)
        {
            this.model = model;
            this.DisplayName = Labels.DesdoblarArticulo;

            LoadArticles(selectedArticle);
        }


        public ICommand SplitCommand
        {
            get
            {
                if (splitCommand == null)
                {
                    splitCommand = new RelayCommand(param => SplitArticle());
                }
                return splitCommand;
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new RelayCommand(param => Cancel());
                }
                return cancelCommand;
            }
        }

        public ICommand AddArticleCommand
        {
            get
            {
                if (selectCommand == null)
                {
                    selectCommand = new RelayCommand(param => AddArticle());
                }
                return selectCommand;
            }
        }

        public ICommand RemoveArticleCommand
        {
            get
            {
                if (removeArticleCommand == null)
                {
                    removeArticleCommand = new RelayCommand(param => RemoveArticle());
                }
                return removeArticleCommand;
            }
        }

        public ICommand SearchCommand
        {
            get
            {
                if (searchCommand == null)
                {
                    searchCommand = new RelayCommand(param => SearchArticles(param as string));
                }
                return searchCommand;
            }
        }

        
        
        public ObservableCollection<Article> LeftArticles 
        {
            get
            {
                return new ObservableCollection<Article>(leftArticles);
            }
        }

        public ObservableCollection<Article> RightArticles
        {
            get
            {
                return new ObservableCollection<Article>(rightArticles);
            }
        }

        public Article SelectedLeftArticle { get; set; }

        public Article SelectedRightArticle { get; set; }

        public Article ArticleToSplit { get; set; }



        private void RemoveArticle()
        {
            var selecteds = rightArticles.Where(x => x.IsSelected);

            foreach (var art in selecteds)
            {
                leftArticles.Add(art);
            }

            rightArticles.RemoveAll(x => selecteds.Select(a => a.Id).Contains(x.Id));
            

            ClearSelections();

            OnPropertyChanged<ArticleMasterSplitPopupViewModel>(p => p.LeftArticles);
            OnPropertyChanged<ArticleMasterSplitPopupViewModel>(p => p.RightArticles);
        }

        private void AddArticle()
        {
            var selecteds = leftArticles.Where(x => x.IsSelected);

            foreach (var art in selecteds)
            {
                rightArticles.Add(art);
            }

            leftArticles.RemoveAll(x => selecteds.Select(a => a.Id).Contains(x.Id));


            ClearSelections();

            OnPropertyChanged<ArticleMasterSplitPopupViewModel>(p => p.LeftArticles);
            OnPropertyChanged<ArticleMasterSplitPopupViewModel>(p => p.RightArticles);
        }

        private void SearchArticles(string criteria)
        {
            List<Article> foundArticles = model.SearchArticles(criteria);

            foundArticles.RemoveAll(x => rightArticles.Select(a => a.Id).Contains(x.Id));

            leftArticles = foundArticles;

            ClearSelections();

            OnPropertyChanged<ArticleMasterSplitPopupViewModel>(p => p.LeftArticles);
        }

        private void Cancel()
        {
            WindowManager.CloseView(this);
        }

        private void SplitArticle()
        {
            if (CanSplit())
            {
                model.SplitArticle(ArticleToSplit, rightArticles.ToList());

                WindowManager.CloseView(this, true);
            }
        }

        private bool CanSplit()
        {
            if (rightArticles.Count < 2)
            {
                Alert msg = new Alert("Debe seleccionar al menos 2 articulos en la lista derecha", "Falta seleccionar artículos", AlertType.Warning);
                msg.ShowDialog();
                return false;
            }

            decimal totalPercent = 0;
            decimal totalMarginPercent = 0;            
            foreach(Article art in rightArticles)
            {
                if (!art.IsValid)
                    return false;

                totalPercent += art.SplitPercentage ?? 0;
                totalMarginPercent += art.MarginSplitPercentage ?? 0;
            }
            
            if(totalPercent != 100)
            {
                Alert msg = new Alert("La suma de los % Ventas debe ser 100%", "Porcentajes invalidos", AlertType.Warning);
                msg.ShowDialog();
                return false;
            }

            if (totalMarginPercent != 100)
            {
                Alert msg = new Alert("La suma de los % Margen debe ser 100%", "Porcentajes invalidos", AlertType.Warning);
                msg.ShowDialog();
                return false;
            }

            return true;
        }

        private void LoadArticles(Article selectedArticle)
        {
            leftArticles = model.SearchArticles(selectedArticle.Category.Name);

            ArticleToSplit = leftArticles.SingleOrDefault(x => x.Id == selectedArticle.Id);

            if (ArticleToSplit != null)
            {
                rightArticles = new List<Article>() { ArticleToSplit };
            }
            else
            {
                rightArticles = new List<Article>();
            }

            ClearSelections();
        }

        private void ClearSelections()
        {
            foreach (var art in leftArticles)
            {
                art.IsSelected = false;
            }

            if (rightArticles != null)
            {
                foreach (var art in rightArticles)
                {
                    art.IsSelected = false;
                }
            }

            List<int> rightIds = RightArticles.Select(x => x.Id).ToList();

            leftArticles.RemoveAll(x => rightIds.Contains(x.Id));

            OnPropertyChanged<ArticleMasterSplitPopupViewModel>(p => p.LeftArticles);
            OnPropertyChanged<ArticleMasterSplitPopupViewModel>(p => p.RightArticles);
        }

    }
}
